package com.chanjet.donkey.service.tree;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.code_factory.jpa.nestedset.JpaNestedSetManager;
import org.code_factory.jpa.nestedset.JpaNode;
import org.code_factory.jpa.nestedset.NestedSetManager;
import org.code_factory.jpa.nestedset.Node;
import org.code_factory.jpa.nestedset.NodeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class NestedSetService implements NestedSetManager {
	@Autowired
	private EntityManager em;
	public void clear() {
	}

	public <T extends NodeInfo> Node<T> createRoot(T root) {
		return newNsm().createRoot(root);
	}
	
	private JpaNestedSetManager newNsm() {
		return new JpaNestedSetManager(em);
	}
	public <T extends NodeInfo> void addChild(T node, T child) {
		new JpaNode<NodeInfo>(node, newNsm()).addChild(child);
	}

	public <T extends NodeInfo> Node<T> fetchTree(Class<T> clazz, int rootId) {
		return new JpaNestedSetManager(em).fetchTree(clazz, rootId);
	}

	public <T extends NodeInfo> Node<T> fetchTree(Class<T> clazz) {
		return new JpaNestedSetManager(em).fetchTree(clazz);
	}

	public <T extends NodeInfo> List<Node<T>> fetchTreeAsList(Class<T> clazz) {
		return new JpaNestedSetManager(em).fetchTreeAsList(clazz);
	}

	public <T extends NodeInfo> List<Node<T>> fetchTreeAsList(Class<T> clazz, int rootId) {
		return new JpaNestedSetManager(em).fetchTreeAsList(clazz, rootId);
	}

	public EntityManager getEntityManager() {
		return em;
	}

	public <T extends NodeInfo> Node<T> getNode(T nodeInfo) {
		return new JpaNestedSetManager(em).getNode(nodeInfo);
	}

	public Collection<Node<?>> getNodes() {
		return new JpaNestedSetManager(em).getNodes();
	}
	
	public NodeInfo findById(Class clazz, Long id) {
		return em.find(clazz, id);
	}

}
